package cn.jwcat.config;

import cn.jwcat.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT过滤器，拦截 /secure的请求
 */
@Component
@Slf4j
public class ReInterceptor implements HandlerInterceptor {
	@Resource
	JwtTokenUtil jwtTokenUtil;

	@Override
	public boolean preHandle(HttpServletRequest request,
													 @NotNull HttpServletResponse response, @NotNull Object handler)
		throws SignatureException, ExpiredJwtException {
		if ("OPTIONS".equals(request.getMethod())) {
			return true;
		}
		System.out.println(request.getRequestURI());
		String JWT = request.getHeader(jwtTokenUtil.getHeader());
		String token = jwtTokenUtil.getTokenFromRequest(request);
		if (null == JWT || null == token) {
			throw new SignatureException("登录失败，请重新登录。");
		}
		Claims tokenClaim = jwtTokenUtil.getTokenClaim(token);
		if (tokenClaim == null || jwtTokenUtil.isTokenExpired(tokenClaim.getExpiration())) {
			throw new SignatureException("登录过期，请重新登录。");
		}
		return true;
	}
}